package com.jic.order.controller.manage;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.order.request.OrderRouteSplitWarehouseAndConditionsRequest;
import com.jic.order.request.OrderRouteSplitWarehouseRequest;
import com.jic.order.response.OrderRouteSplitWarehouseResponse;
import com.jic.common.base.vo.PageResult;
import com.jic.order.service.OrderRouteSplitWarehouseService;
import com.jic.order.utils.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "路由分仓规则管理")
@RequestMapping(value = "orderRouteSplitWarehouse")
@RestController
public class OrderRouteSplitWarehouseController {

    @Autowired
    OrderRouteSplitWarehouseService orderRouteSplitWarehouseService;
    @Resource
    private ManagerMerchantApi managerMerchantApi;


    @ApiOperation(value = "路由分仓规则分页查询")
    @RequestMapping(value = "queryPage", method = RequestMethod.POST)
    public RestResult<PageResult<OrderRouteSplitWarehouseResponse>> queryPage(@RequestBody OrderRouteSplitWarehouseRequest form) {
        log.info("开始调用路由分仓规则分页，{}", JSON.toJSONString(form));
        Page pageQuery = new Page();
        pageQuery.setLimit(form.getLimit());
        pageQuery.setStart(form.getStart());
        DeptTypeEnums deptType = form.getAdminOperate().getDeptType();
        if (deptType.getCode() != 0) {
            form.setDeptId(form.getDeptId());
        }
        OrderRouteSplitWarehouseRequest orderRouteSplitWarehouse = BeanUtil.copy(form, OrderRouteSplitWarehouseRequest.class);
        PageResult<OrderRouteSplitWarehouseResponse> result = orderRouteSplitWarehouseService.queryPage(orderRouteSplitWarehouse, pageQuery);

        List<OrderRouteSplitWarehouseResponse> orderRouteSplitWarehouseResponseList = result.getRows().stream().map(temp -> {
            OrderRouteSplitWarehouseResponse orderRouteSplitWarehouseResponse = BeanUtil.copy(temp, OrderRouteSplitWarehouseResponse.class);
            if(null != temp.getDeptId()){
                RestResult<List<MerchantRequest>> listRestResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                    add(Long.valueOf(temp.getDeptId()));
                }});
                if(CollectionUtils.isNotEmpty(listRestResult.getData())){
                    orderRouteSplitWarehouseResponse.setMerchantName(listRestResult.getData().get(0).getName());
                }
            }

            return orderRouteSplitWarehouseResponse;
        }).filter(item -> item != null).collect(Collectors.toList());

        PageResult<OrderRouteSplitWarehouseResponse> pageResult = new PageResult<>();
        pageResult.setRows(orderRouteSplitWarehouseResponseList);
        pageResult.setTotal(result.getTotal());
        return RestResult.success(pageResult);
    }

    @ApiOperation(value = "路由分仓规则修改/新增")
    @RequestMapping(value = "editorderRouteSplitWarehouse", method = RequestMethod.POST)
    public RestResult editorderRouteSplitWarehouse(@RequestBody OrderRouteSplitWarehouseAndConditionsRequest form) {
        log.info("开始调用路由分仓规则修改/新增，{}", JSON.toJSONString(form));
        RestResult restResult = new RestResult<>();
        //TODO 将merchantId存入deptId
        form.setDeptId(form.getMerchantId());
        try {
            //修改
            if (form.getId() > 0) {
                form.setUpdater(form.getAdminOperate().getOperator().intValue());
                form.setUpdaterName(form.getAdminOperate().getOperateName());
                long flag = orderRouteSplitWarehouseService.update(form);
                restResult = RestResult.success(restResult);
            } else {
                form.setCreator(form.getAdminOperate().getOperator().intValue());
                form.setCreatorName(form.getAdminOperate().getOperateName());
                long flag = orderRouteSplitWarehouseService.insert(form);
                restResult = RestResult.success(restResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
            restResult = RestResult.error("9999", e.getLocalizedMessage());
        }
        return restResult;
    }

    @ApiOperation(value = "删除路由分仓规则")
    @ResponseBody
    @PostMapping(value = "/deleteorderRouteSplitWarehouse")
    public RestResult delProductSaleAreaRelation(Long id) {
        log.info("开始调用路由分仓规则删除，{}", JSON.toJSONString(id));
        return RestResult.success(orderRouteSplitWarehouseService.delete(id));
    }

    @ApiOperation(value = "生成路由分仓规则编码")
    @ResponseBody
    @PostMapping(value = "/createCode")
    public RestResult createCode() {
        log.info("开始调用路由分仓规则编码生成，{}", JSON.toJSONString(""));
        return RestResult.success("OR" + new Date().getTime());
    }

    @ApiOperation(value = "路由分仓规则批量删除")
    @PostMapping(value = "/deleteConditions")
    @ResponseBody
    public RestResult<String> deleteConditions(@RequestBody OrderRouteSplitWarehouseAndConditionsRequest form) {
        log.info("开始调用路由分仓规则批量删除，{}", JSON.toJSONString(form));
        RestResult result = new RestResult();
        String ids = form.getIds();
        try {
            if (ids != null) {
                String[] strings = ids.split(",");
                for (String string : strings) {
                    long id = Long.valueOf(string);
                    orderRouteSplitWarehouseService.delete(id);
                }

            }
        } catch (Exception e) {

            return RestResult.error("9999", e.getLocalizedMessage());
        }
        return RestResult.success("0000");
    }

    @ApiOperation(value = "批量停用路由分仓规则")
    @ResponseBody
    @PostMapping(value = "/ediStatus")
    public RestResult<String> ediStatus(@RequestBody OrderRouteSplitWarehouseAndConditionsRequest form) {
        log.info("开始调用批量停用路由分仓规则，{}", JSON.toJSONString(form));
        RestResult result = new RestResult();
        String ids = form.getIds();
        try {
            if (ids != null) {
                String[] strings = ids.split(",");
                for (String string : strings) {
                    long id = Long.valueOf(string);
                    orderRouteSplitWarehouseService.editStatus(ids);
                }
            }
        } catch (Exception e) {
            return RestResult.error("9999", e.getLocalizedMessage());
        }
        return RestResult.success("0000");
    }
}
